import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
    ProForm,
    ProFormText,
    ProFormSelect,
    ProFormSwitch,
    ProFormUploadButton,
    ProFormDigit,
    ProFormTextArea,
} from '@ant-design/pro-components';
import { Card, Form, Input, InputNumber, Space, Button, message, Row, Col, Select, Empty } from 'antd';
import { useParams, history, useLocation } from 'umi';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { createProduct, getProductAttributeList, getProductCategory, getProductDetail, updateProduct } from '@/services/ant-design-pro/product';
import Myupload from '@/components/MyUpload';
import ProductTagSelector from '@/components/ProductTagSelector';

interface ProductFormData {
    id?: string;
    title: string;
    categoryId: string;
    category?: {
        id: string;
        name: string;
    };
    status: number;
    image: string;
    description: string;
    type: number;
    price?: number;
    stock: number;
    canBuy: boolean;
    tags?: string[];
    variants?: Array<{
        id?: string;
        price: number;
        stock: number;
        attValues: string[];
        status: number;
    }>;
    attributeGroups?: Array<{
        id: string;
        name: string;
        attributeValues: Array<{
            id: string;
            value: string;
            label: string;
        }>;
    }>;
}

// 组件接口定义
interface SkuItemsProps {
    value?: any;
    onChange?: (value: any) => void;
    attributeOptions: any[];
    currentAttribute: any;
    onAttributeChange: (attribute: any) => void;
}

// SkuItems 组件定义
const SkuItems: React.FC<SkuItemsProps> = ({
    attributeOptions,
    currentAttribute,
    onAttributeChange,
}) => {
    if (!attributeOptions || attributeOptions.length === 0) {
        return <div>暂无可用规格</div>;
    }
    console.log('currentAttribute', currentAttribute);
    return (
        <div>
            <Select
                options={attributeOptions}
                value={currentAttribute?.id}
                style={{ width: '100%', marginBottom: 16 }}
                placeholder="请选择规格类型"
                onChange={(value) => {
                    const selected = attributeOptions.find(item => item.value === value);
                    console.log('selected', selected);
                    if (selected?.item) {
                        onAttributeChange(selected.item);
                    }
                }}
            />

            {currentAttribute && currentAttribute.attributeValues?.length > 0 ? (
                <Row gutter={16}>
                    {currentAttribute.attributeValues.map((item: any, index: number) => (
                        <Col span={12} key={item.id || index}>
                            <Card
                                title={item.value || item.label || item.attributeValues?.[0]?.value}
                                size="small"
                                style={{ marginBottom: 16 }}
                            >
                                <Form.Item label="id" name={['variants', index, 'id']} hidden>
                                    <Input />
                                </Form.Item>
                                <Form.Item label="id" name={['variants', index, 'attributeValues']} hidden>
                                    <Input />
                                </Form.Item>
                                <Form.Item
                                    rules={[{ required: true, message: '请输入价格' }]}
                                    label="价格"
                                    name={['variants', index, 'price']}
                                >
                                    <InputNumber
                                        style={{ width: '100%' }}
                                        min={0}
                                        precision={2}
                                        placeholder="请输入价格"
                                    />
                                </Form.Item>
                                <Form.Item
                                    rules={[{ required: true, message: '请输入库存' }]}
                                    label="库存"
                                    name={['variants', index, 'stock']}
                                >
                                    <InputNumber
                                        style={{ width: '100%' }}
                                        min={0}
                                        placeholder="请输入库存"
                                    />
                                </Form.Item>
                                <Form.Item
                                    hidden
                                    initialValue={[item.id]}
                                    name={['variants', index, 'attValues']}
                                >
                                    <Input />
                                </Form.Item>
                                <Form.Item
                                    hidden
                                    initialValue={1}
                                    name={['variants', index, 'status']}
                                >
                                    <Input />
                                </Form.Item>
                            </Card>
                        </Col>
                    ))}
                </Row>
            ) : (
                currentAttribute && <Empty description="该规格暂无选项" />
            )}
        </div>
    );
};

const ProductDetail: React.FC = () => {
    const [form] = Form.useForm();
    const { id } = useParams<{ id: string }>();
    const [isEdit] = useState(() => {
        return typeof id === 'string' && id !== 'new';
    });
    const [categoryOptions, setCategoryOptions] = useState<{ label: string; value: string }[]>([]);
    const [attributeOptions, setAttributeOptions] = useState<{ label: string; value: string; item: any }[]>([]);
    const [currentAttribute, setCurrentAttribute] = useState<any>(null);
    const [isMultiStyle, setIsMultiStyle] = useState(false);

    // 初始化商品分类
    const initCategories = async () => {
        try {
            const resp = await getProductCategory();
            const { list } = resp?.data;
            const options = list.map((item: any) => ({
                label: item.name,
                value: item.id,
            }));
            setCategoryOptions(options);
        } catch (error) {
            message.error('获取商品分类失败');
        }
    };

    // 初始化属性列表
    const initAttributes = async () => {
        try {
            const resp = await getProductAttributeList();
            if (resp?.data?.list) {
                const { list } = resp.data;
                const options = list.map((item: any) => ({
                    label: item.name,
                    value: item.id,
                    item: item,
                }));
                setAttributeOptions(options);
                console.log('属性选项：', options);
            } else {
                console.error('获取属性列表返回数据格式不正确', resp);
            }
        } catch (error) {
            console.error('获取规格列表失败', error);
            message.error('获取规格列表失败');
        }
    };

    // 加载商品详情
    const loadProductDetail = async () => {
        if (isEdit && id && id !== 'new') {
            try {
                const resp = await getProductDetail(id);
                const data = resp?.data;

                if (data) {
                    console.log('商品详情：', data);

                    // 处理表单数据
                    const formData = {
                        ...data,
                        categoryId: data.category?.id,
                        isMultiStyle: !!data.attributeGroups?.[0],
                        tags: data?.tagList ? data?.tagList?.map((tag: any) => tag?.id) : []
                    };

                    // 设置多款式状态
                    setIsMultiStyle(!!data.attributeGroups?.[0]);

                    // 如果有规格组，设置当前规格
                    if (data.attributeGroups?.[0]) {
                        const attributeGroup = data.attributeGroups[0];
                        console.log('规格组：', attributeGroup);

                        setCurrentAttribute({
                            ...attributeGroup,
                            attributeValues: data.variants || []
                        });
                    }

                    // 设置表单值
                    form.setFieldsValue(formData);
                }
            } catch (error) {
                console.error('获取商品详情失败', error);
                message.error('获取商品详情失败');
            }
        }
    };

    const handleChangeAttribute = (attribute: any) => {
        console.log('attribute', attribute);
        setCurrentAttribute(attribute);

        const variants = attribute.attributeValues.map((item: any) => ({
            price: 0,
            stock: 100,
            attValues: [item.id],
            status: 1
        }));
        console.log('variants', variants);
        form.setFieldsValue({
            variants: variants
        });
    }

    useEffect(() => {
        // 初始化分类和属性列表
        initCategories();
        initAttributes();

        // 如果是编辑模式，加载详情
        loadProductDetail();
    }, [id]);

    // 处理表单提交
    const handleSubmit = async (values: any) => {
        console.log('values', values);
        try {
            const submitData = { ...values, };
            console.log('submitData', submitData);
            
            // 处理标签数据
            if (submitData.tags && Array.isArray(submitData.tags)) {
                submitData.tags = submitData.tags;
            } else {
                submitData.tags = [];
            }
            
            if (submitData.variants?.length > 0) {
                submitData.attributesValue = [{
                    id: currentAttribute?.id,
                    values: submitData.variants.map((item: any) => {
                        return item?.attributeValues?.[0]?.id || item.attValues[0]
                    }).filter(Boolean),
                }];

                submitData.variants = submitData.variants.map((item: any) => ({
                    ...item,
                    price: Number(item.price || 0),
                    stock: Number(item.stock || 0),
                    attValues: [item?.attributeValues?.[0]?.id || item.attValues[0]]
                }));
            }

            console.log('[submitData]', submitData);
            const resp = await (isEdit ? updateProduct : createProduct)(submitData);
            if (resp?.code === 1) {
                return false;
            }
            message.success(`${isEdit ? '编辑' : '创建'}成功`);
            history.push('/product/list');
            return true;
        } catch (error) {
            console.log('error', error)
            message.error(`${isEdit ? '编辑' : '创建'}失败`);
            return false;
        }
    };
    console.log('currentAttribute   ', currentAttribute);
    return (
        <PageContainer title={isEdit ? '编辑商品' : '新增商品'}>
            <ProForm
                form={form}
                onFinish={handleSubmit}
                submitter={{
                    render: (props, dom) => (
                        <div style={{ marginTop: 24, textAlign: 'right' }}>
                            <Button onClick={() => history.push('/product/list')} style={{ marginRight: 8 }}>
                                取消
                            </Button>
                            {dom[1]}
                        </div>
                    ),
                }}
            >
                <Row gutter={24}>
                    <Col span={16}>
                        <Card title="基本信息" bordered={false}>
                            <ProFormText
                                label="名称"
                                name="title"
                                rules={[{ required: true }]}
                            />

                            <ProFormSelect
                                label="商品分类"
                                name="categoryId"
                                options={categoryOptions}
                                rules={[{ required: true }]}
                            />

                            <Form.Item
                                label="封面图"
                                name="image"
                            >
                                <Myupload />
                            </Form.Item>

                            <ProFormTextArea
                                label="描述"
                                name="description"
                            />

                            <ProFormSelect
                                label="类型"
                                name="type"
                                initialValue={1}
                                options={[{ label: '实体商品', value: 1 }]}
                                rules={[{ required: true }]}
                            />

                            <ProFormDigit
                                label="库存"
                                name="stock"
                                initialValue={100}
                                rules={[{ required: true }]}
                            />

                            <Form.Item
                                label="商品标签"
                                name="tags"
                                initialValue={[]}
                            >
                                <ProductTagSelector />
                            </Form.Item>

                            <ProFormDigit name="id" hidden />
                        </Card>

                        {/* 款式信息独立卡片 */}
                        <Card
                            title="款式信息"
                            style={{ marginTop: 24 }}
                            bordered={false}
                        >
                            <ProFormSwitch
                                name="isMultiStyle"
                                label="是否多款式商品"
                                initialValue={false}
                                fieldProps={{
                                    onChange: (checked) => setIsMultiStyle(checked),
                                }}
                            />

                            {isMultiStyle ? (
                                <Form.Item label="SKU项" name="attributesValue">
                                    <SkuItems
                                        attributeOptions={attributeOptions}
                                        currentAttribute={currentAttribute}
                                        onAttributeChange={handleChangeAttribute}
                                    />
                                </Form.Item>
                            ) : (
                                <ProFormDigit
                                    label="价格"
                                    name="price"
                                    rules={[{ required: !isMultiStyle, message: '请输入商品价格' }]}
                                    min={0}
                                    fieldProps={{
                                        precision: 2,
                                    }}
                                />
                            )}
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card title="商品状态" bordered={false}>
                            <ProFormSelect
                                label="上下架"
                                name="status"
                                initialValue={1}
                                rules={[{ required: true }]}
                                options={[
                                    { label: '上架', value: 1 },
                                    { label: '下架', value: 0 },
                                ]}
                            />

                            <ProFormSwitch
                                label="是否能购买"
                                name="canBuy"
                                initialValue={true}
                                rules={[{ required: true }]}
                            />
                        </Card>
                    </Col>
                </Row>
            </ProForm>
        </PageContainer>
    );
};

export default ProductDetail;
